# -*- coding: utf-8 -*-
# @Time    : 2023/11/21 9:22
# @Author  : yan.wei
# @Email   : 13675196684@163.com
# @File    : OA_CourseScheduleUtil.py
# @Software: PyCharm

# 第三方库版本说明：
# pyinstaller == 6.2.0
# pandas == 2.1.3

# pyinstaller是通过UPX进行压缩操作，如果缺少upx，会导致exe变大
# 下载https://upx.github.io/
# 解压到pipenv虚拟环境对应的目录下，\项目名\Scripts
# 装好UPX之后，打包的exe比未安装UPX的exe小了

# 打包成exe
# pyinstaller -F -w xxx.py


import os
import sys
import re
import subprocess
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QTextBrowser, QSplitter, QDesktopWidget,  QHBoxLayout, QLineEdit, QCheckBox
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt
import openpyxl


class CourseScheduleApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 添加标题
        self.setWindowTitle('课表自动生成工具v1.0')
        # self.setWindowIcon(QIcon(r'E:\NoteAdding\test.ico'))  # 替换为实际图标文件的路径，用绝对路径，不然会不显示
        # self.setWindowIcon(QIcon('logo/new.ico'))  # 替换为实际图标文件的路径
        self.setGeometry(100, 100, 800, 400)  # 调整窗口大小
        self.setStyleSheet(
            "QMainWindow { background-color: #f0f0f0; }"
            # "QPushButton { background-color: #009ACD; color: white; padding: 8px; font-size: 12px; border: none; }"
            # "QPushButton:hover { background-color: #2980b9; }"
            # "QRadioButton { color: #2c3e50; }"
            "QWidget { font-family: '微软雅黑'; }"
        )
        font = QFont()
        font.setPointSize(14)  # 设置字体大小为14
        self.setFont(font)

        # 获取屏幕的几何信息
        # screen_geometry = QDesktopWidget().screenGeometry()
        #
        # # 计算窗口的位置使其居中
        # window_width = self.frameGeometry().width()
        # window_height = self.frameGeometry().height()
        # x = (screen_geometry.width() - window_width) / 2
        # y = (screen_geometry.height() - window_height) / 2
        # self.move(int(x), int(y))

        # 将界面进行分割
        # 水平分割
        self.splitter = QSplitter(Qt.Horizontal)
        # 垂直分割
        # self.splitter = QSplitter(Qt.Vertical)

        self.splitter.setOpaqueResize(True)
        self.splitter.setHandleWidth(1)
        self.setCentralWidget(self.splitter)


        # 编写左侧代码UI
        self.leftWidget = QWidget()
        self.leftLayout = QVBoxLayout()
        self.leftWidget.setLayout(self.leftLayout)
        self.splitter.addWidget(self.leftWidget)

        # 编写左侧代码UI
        self.leftinfoLabel = QLabel('工具一：\n开班课表自动生成工具',  self)
        self.leftinfoLabel.setStyleSheet('color: #7171C6; font-size: 18px; font-weight: bold;')
        self.leftLayout.addWidget(self.leftinfoLabel)

        # 添加一个读取文件夹中所有文件的按钮
        self.openFolderButton = QPushButton('打开csv文件存放目录', self)
        self.openFolderButton.clicked.connect(self.open_csv_folder)
        self.leftLayout.addWidget(self.openFolderButton)

        # 添加一个打开文件保存目录的一个按钮
        self.openFolderButton = QPushButton('打开文件保存目录', self)
        self.openFolderButton.clicked.connect(self.open_save_folder)
        self.leftLayout.addWidget(self.openFolderButton)

        # 添加一个启动按钮
        self.startButton = QPushButton('启动', self)
        self.startButton.clicked.connect(self.mianstartExtraction)
        self.leftLayout.addWidget(self.startButton)

        # ResultTextEdit
        self.leftResultTextEdit = QTextBrowser(self)
        self.leftResultTextEdit.setOpenExternalLinks(True)
        self.leftLayout.addWidget(self.leftResultTextEdit)


        # # 编写中间代码UI
        # self.middleWidget = QWidget()
        # self.middleLayout = QVBoxLayout()
        # self.middleWidget.setLayout(self.middleLayout)
        # self.splitter.addWidget(self.middleWidget)
        #
        # self.middleinfoLabel = QLabel('工具二：\n开班课表自动生成工具',  self)
        # self.middleinfoLabel.setStyleSheet('color: #7171C6; font-size: 18px; font-weight: bold;')
        # self.middleLayout.addWidget(self.middleinfoLabel)
        #
        # # 添加一个读取文件夹中所有文件的按钮
        # self.openFolderButton = QPushButton('打开csv文件存放目录', self)
        # self.openFolderButton.clicked.connect(self.open_csv_folder)
        # self.middleLayout.addWidget(self.openFolderButton)
        #
        # # 添加一个打开文件保存目录的一个按钮
        # self.openFolderButton = QPushButton('打开文件保存目录', self)
        # self.openFolderButton.clicked.connect(self.open_save_folder)
        # self.middleLayout.addWidget(self.openFolderButton)
        #
        # # 添加一个启动按钮
        # self.startButton = QPushButton('启动', self)
        # self.startButton.clicked.connect(self.mianstartExtraction)
        # self.middleLayout.addWidget(self.startButton)
        #
        # # ResultTextEdit
        # self.mainResultTextEdit = QTextBrowser(self)
        # self.mainResultTextEdit.setOpenExternalLinks(True)
        # self.middleLayout.addWidget(self.mainResultTextEdit)



        # 编写右侧代码UI
        self.rightWidget = QWidget()
        self.rightLayout = QVBoxLayout()
        self.rightWidget.setLayout(self.rightLayout)
        self.splitter.addWidget(self.rightWidget)

        self.rightinfoLabel = QLabel('工具三：\n开班课表自动生成工具',  self)
        self.rightinfoLabel.setStyleSheet('color: #7171C6; font-size: 18px; font-weight: bold;')
        self.rightLayout.addWidget(self.rightinfoLabel)

        # 添加一个读取文件夹中所有文件的按钮
        self.openFolderButton = QPushButton('打开csv文件存放目录', self)
        self.openFolderButton.clicked.connect(self.open_csv_folder)
        self.rightLayout.addWidget(self.openFolderButton)

        # 添加一个打开文件保存目录的一个按钮
        self.openFolderButton = QPushButton('打开文件保存目录', self)
        self.openFolderButton.clicked.connect(self.open_save_folder)
        self.rightLayout.addWidget(self.openFolderButton)

        # 添加一个启动按钮
        self.startButton = QPushButton('启动', self)
        self.startButton.clicked.connect(self.mianstartExtraction)
        self.rightLayout.addWidget(self.startButton)

        # ResultTextEdit
        self.rightResultTextEdit = QTextBrowser(self)
        self.rightResultTextEdit.setOpenExternalLinks(True)
        self.rightLayout.addWidget(self.rightResultTextEdit)


    # 编写open_floder函数
    def open_csv_folder(self):
        # 打开文件夹
        folder_path = QFileDialog.getExistingDirectory(self)
        if folder_path:
            self.open_folder_path = folder_path
            self.mainResultTextEdit.append(f'已选择的CSV文件存放文件夹: {self.open_folder_path}')

    def open_save_folder(self):
        # 打开文件夹
        folder_path = QFileDialog.getExistingDirectory(self)
        if folder_path:
            self.save_folder_path = folder_path
            self.mainResultTextEdit.append(f'已选择的结果保存文件夹: {self.save_folder_path}')

    def mianstartExtraction(self):
        # if hasattr(self, 'pptFilePath', 'wordFilePath'):
        if hasattr(self, 'open_folder_path') and hasattr(self, 'save_folder_path'):
            self.mainResultTextEdit.append('\n文件处理中...')
            folder_path = CsvUtil(self.open_folder_path, self.save_folder_path).merge_csv()
            # self.rightResultTextEdit.append(f'\n输出文件夹: <a href="file:///{folder_path}">{folder_path}</a>')
            self.mainResultTextEdit.append(f'\n输出文件: {folder_path}')
            # 打开文件夹
            subprocess.Popen(['explorer', os.path.abspath(os.path.dirname(folder_path))],
                             shell=True)  # Windows 上使用 "explorer"
        else:
            self.mainResultTextEdit.append('\n请先选择一个PPT文件。')
class CsvUtil:
    def __init__(self, origin_folder_path, result_folder_path):
        self.origin_folder_path = origin_folder_path
        self.result_folder_path = result_folder_path
        # self.csv_files = [file for file in os.listdir(origin_folder_path) if file.endswith('.csv')]

    def merge_csv(self):

        csv_files = [file for file in os.listdir(self.origin_folder_path) if file.endswith('.csv')]
        merged_data = pd.read_csv(os.path.join(self.origin_folder_path, csv_files[0]))

        for file in csv_files[1:]:
            file_path = os.path.join(self.origin_folder_path, file)
            data_to_append = pd.read_csv(file_path)
            merged_data = pd.concat([merged_data, data_to_append], ignore_index=True)
        # 提取合并后的文件名，这里使用 csv_files[0]中的文件名
        merged_file_name = csv_files[0].split('.')[0] + '_merged'
        output_file = os.path.join(self.result_folder_path, merged_file_name+ ".csv")
        merged_data.to_csv(output_file, index=False)
        return output_file

    # 拆分文件成指定份数，返回拆分后的文件数，并在指定目录下生成拆分后的文件
    def split_csv(self, file_name, split_size):
        file_path = os.path.join(self.origin_folder_path, file_name)
        data = pd.read_csv(file_path)
        data_size = len(data)
        split_num = data_size // split_size
        if data_size % split_size != 0:
            split_num += 1
        for i in range(split_num):
            start = i * split_size
            end = start + split_size
            if i == split_num - 1:
                end = data_size
            split_data = data[start:end]
            output_file = os.path.join(self.result_folder_path, f"split_{i}.csv")
            split_data.to_csv(output_file, index=False)
        return split_num

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = CourseScheduleApp()
    mainWindow.show()
    sys.exit(app.exec_())

